/*
 * @Description: 
 * @Author: duan_shuangjun 丶
 * @Date: 2025-09-17 16:07:35
 * @LastEditTime: 2025-09-17 18:20:45
 */
import { dbUtils } from '../core'

export interface StoreShopPrinterSettingRow {
    setting_id: string
    key: string
    describe: string
    values: string
    store_id: string
    shop_id: string
    printer_id: string
    create_time: number
    update_time: number
}

export const storeShopPrinterSettingRepository = {
    upsertBatch(rows: StoreShopPrinterSettingRow[]): void {
        if (!rows || rows.length === 0) return
        dbUtils.transaction(() => {
            // SQL列（包含保留字的转义）与逻辑键分离，避免键名不匹配
            const sqlColumns = ['setting_id', '"key"', '"describe"', '"values"', 'store_id', 'shop_id', 'printer_id', 'create_time', 'update_time']
            const valueKeys: Array<keyof StoreShopPrinterSettingRow> = ['setting_id', 'key', 'describe', 'values', 'store_id', 'shop_id', 'printer_id', 'create_time', 'update_time']

            const placeholders = sqlColumns.map(() => '?').join(', ')
            const updateSet = sqlColumns
                .filter(c => c !== 'setting_id')
                .map(c => `${c}=excluded.${c}`)
                .join(', ')

            const sql = `INSERT INTO store_shop_printer_setting (${sqlColumns.join(', ')}) VALUES (${placeholders})
            ON CONFLICT(setting_id) DO UPDATE SET ${updateSet}, updated_at=CURRENT_TIMESTAMP`

            for (const row of rows) {
                const vals = valueKeys.map((k) => {
                    let v: any = (row as any)?.[k]
                    if (k === 'store_id' || k === 'shop_id' || k === 'printer_id') {
                        return v ?? '0'
                    }
                    if (k === 'key' || k === 'describe') {
                        return v ?? ''
                    }
                    if (k === 'values') {
                        // 值可能是对象/数组或已是字符串，统一存字符串，保障 NOT NULL
                        if (v === undefined || v === null) return '[]'
                        if (typeof v === 'string') return v
                        try { return JSON.stringify(v) } catch { return '[]' }
                    }
                    if (k === 'create_time' || k === 'update_time') {
                        return typeof v === 'number' ? v : 0
                    }
                    // setting_id 必须有
                    if (k === 'setting_id') {
                        return v ?? ''
                    }
                    return v
                })
                dbUtils.execute(sql, vals)
            }
        })
    }
}

export default storeShopPrinterSettingRepository


